package com.liesheng.haylou.bluetooth;

import android.bluetooth.BluetoothDevice;

import com.liesheng.daemonlib.LogUtil;
import com.liesheng.haylou.event.DialogCloseEvent;
import com.liesheng.haylou.utils.NumUtil;
import com.liesheng.haylou.utils.sp.SpUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.Arrays;
import java.util.List;

/**
 * Date:2019/12/9
 * <p>
 * Author:wuzhiguang
 * <p>
 * Description:
 * 广播包内容解析
 */
public class BleDataInfo {

    private final String HAYOU_FACTORYFLAG = "4C53";
    private final String HAYOU_SPECIFICVALUE = "3C";

    /**
     * 广播包中是否含有厂商指定的服务,如果没有则代表不是指定的设备,后面的数据数据解析就不用进行
     */
    private boolean hasHayLouServiceUuid = false;//

    private String factoryFlag;//耳机厂商标识+特征值字段 (byte2～byte3 共2个字节)
    private String specificValue;//特殊值 (byte4 共1个字节)
    private String pType;//产品类型 (byte5 1个字节)
    private String pId;//产品型号 (byte6 1个字节)
    private int checkValue;// 校验字节(byte7) -- 该值是byte8~byte12值相加 取低8位bit值
    private int computeValue;//自己计算得出的值 , 需与checkValue来做比较
    private String rLaddress;//固定为 右耳机mac地址+左耳机mac地址(byte16~byte21 + byte23~byte28),用来标识唯一的蓝牙设备
    private String leftAddress;//左耳机mac地址( byte23~byte28)
    private String rightAddress;//右耳机mac地址( byte16~byte21)
    private String adCount;//广播计数(byte13) 当本地记录的数值与该值不等时则需要弹窗
    private int rigthConn;//右耳是否可连接 非0-可连接 0-不可连接  (byte8 的 bit7位)
    private int rigthFound;//右耳是否可发现 非0-可发现 0-不可发现  (byte8 的 bit5位)
    private int leftConn;//右耳是否可连接 非0-可连接 0-不可连接  (byte8 的 bit6位)
    private int leftFound;//右耳是否可发现 非0-可发现 0-不可发现  (byte8 的 bit4位)
    private int inBox;//是否拿出盒子的标志位(1--拿出了盒子  0--在盒子里面),在盒子里才弹窗  (byte9 的 bit5位)
    private int boxOpen;// (byte9 的 bit1位) 盒子是否打开的状态 (1--盒子打开  0--盒子关闭),盒子打开才弹窗或被搜索到,盒子关闭后盒子关闭后,关闭已弹出的对话框关闭已弹出的对话框

    private int[] batteries;//盒子-左耳机-右耳机  电量百分比  , 分别对应byte14、byte22、byte15 的 bit0~bit6
    private int[] charging;//盒子-左耳机-右耳机  是否在充电,1为充电  , 分别对应byte14、byte22、byte15 的 bit7


    //ble广播包数据中 厂商自定义的数据(须包含前两个字节---长度和类型ff)  manufacturerData
    private String manufacturerHex;

    private BluetoothDevice dev;

    private BleDataInfo(String manufacturerHex, BluetoothDevice dev) {
        hasHayLouServiceUuid = true;
        this.manufacturerHex = manufacturerHex.toUpperCase().replaceAll(" ", "");
        String name = dev != null ? dev.getName() : "name";
        if (name != null && name.contains("T19-"))
            LogUtil.d("BleDataInfo--", "name = " + name + " ****  manufacturerHex=" + manufacturerHex);
        this.dev = dev;
    }

    public BleDataInfo() {
        hasHayLouServiceUuid = false;
    }

    public static BleDataInfo create(byte[] scanData, BluetoothDevice dev) {

        if (!ScanRecordUtil.hasService(scanData, BleUUIDs.SERVICE)) {
            return new BleDataInfo();
        }

        String[] manufacturerData = ScanRecordUtil.getManufacturerData(scanData);
        String hex = Arrays.toString(manufacturerData).replaceAll(",", "");
        hex = hex.substring(1, hex.length() - 1);//去掉首尾的中括号 []
        BleDataInfo info = new BleDataInfo(hex, dev);
        info.decodeHex();

        return info;
    }

    //过滤其它的设备
    public boolean canBeSearched() {
        return boxOpen != 0 && hasHayLouServiceUuid && HAYOU_FACTORYFLAG.equals(factoryFlag) && HAYOU_SPECIFICVALUE.equals(specificValue) && checkValue == computeValue;
//        return hasHayLouServiceUuid && HAYOU_FACTORYFLAG.equals(factoryFlag) && HAYOU_SPECIFICVALUE.equals(specificValue);
    }

    //要不要弹窗显示
    public boolean isShowBleDialog() {

        if (!canBeSearched() || inBox != 0 || rigthFound == 0 || rigthConn == 0 || leftConn == 0 || leftFound == 0)
            return false;
        String count = SpUtil.getString(rightAddress + leftAddress, "-1");
        return !adCount.equals(count);
    }

    //如果已经弹窗了 ,盒子关闭后要自动消失
    public void checkShouldCloseBleDialog() {
        if (boxOpen == 0) {
            EventBus.getDefault().post(new DialogCloseEvent(rightAddress + leftAddress));
        }
    }


    private void decodeHex() {
        if (manufacturerHex.length() < 29 * 2)
            return;
        factoryFlag = manufacturerHex.substring(4, 8);
        specificValue = manufacturerHex.substring(8, 10);
        pType = manufacturerHex.substring(10, 12);
        pId = manufacturerHex.substring(12, 14);
        checkValue = NumUtil.hex2Int(manufacturerHex.substring(14, 16));
        adCount = manufacturerHex.substring(26, 28);
        leftAddress = manufacturerHex.substring(46, 58);
        rightAddress = manufacturerHex.substring(32, 44);
//        rLaddress = manufacturerHex.substring(32, 44) + manufacturerHex.substring(46, 58);
        rLaddress = rightAddress + leftAddress;


        //(byte8 的 bit7位)
        rigthConn = NumUtil.hex2Int(manufacturerHex.substring(16, 18)) & 0b10000000;
        //(byte8 的 bit5位)
        rigthFound = NumUtil.hex2Int(manufacturerHex.substring(16, 18)) & 0b00100000;
        //(byte8 的 bit6位)
        leftConn = NumUtil.hex2Int(manufacturerHex.substring(16, 18)) & 0b01000000;
        //(byte8 的 bit4位)
        leftFound = NumUtil.hex2Int(manufacturerHex.substring(16, 18)) & 0b00010000;
        //(byte9 的 bit5位)
        inBox = NumUtil.hex2Int(manufacturerHex.substring(18, 20)) & 0b00100000;
        //(byte9 的 bit1位)
        boxOpen = NumUtil.hex2Int(manufacturerHex.substring(18, 20)) & 0b00000010;
        //计算computeValue
        computeValue = 0;
        //byte8~byte12相加取低8位
        for (int i = 0; i < 5; i++) {
            String h = manufacturerHex.substring((i + 8) * 2, (i + 8) * 2 + 2);
            computeValue += NumUtil.hex2Int(h);
        }
        computeValue = computeValue & 0b11111111;

        //获取电量及充电状态
        String batteryHex = manufacturerHex.substring(44, 46) + manufacturerHex.substring(30, 32) + manufacturerHex.substring(28, 30);
        List<int[]> list = ScanRecordUtil.getBattey(batteryHex);
        batteries = new int[3];
        batteries[0] = list.get(0)[1];
        batteries[1] = list.get(1)[1];
        batteries[2] = list.get(2)[1];

        charging = new int[3];
        charging[0] = list.get(0)[0];
        charging[1] = list.get(1)[0];
        charging[2] = list.get(2)[0];
    }


    //每两个字符用 冒号 隔开
    private String formateAddress(String addressHex) {
        String regex = "(.{2})";
        addressHex = addressHex.replaceAll(regex, "$1:");
        addressHex = addressHex.substring(0, addressHex.length() - 1);
        System.out.println(addressHex);
        //  打印的结果为00:00:00:00:00:00

        return addressHex;
    }

    public BluetoothDevice getDev() {
        return dev;
    }

    public String getrLaddress() {
        return rLaddress;
    }

    public String getAdCount() {
        return adCount;
    }

    public int[] getBatteries() {
        return batteries;
    }

    public int[] getCharging() {
        return charging;
    }

    public String getLeftAddress() {
        return formateAddress(leftAddress);
    }

    public String getRightAddress() {
        return formateAddress(rightAddress);
    }
}
